<?php

namespace App\Exports\Cruise;

use App\Models\Cruise\CruiseCheckDetailModel;
use App\Models\Cruise\CruiseCheckTaskGroupModel;
use App\Models\Cruise\CruiseCheckTaskModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\Shop\ShopModel;
use App\Remote\Rms\RmsShopRemote;
use App\Service\Common\ExportService;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromArray;

class CruiseCheck3Export implements FromArray
{

    public Collection $originalData;
    public Collection $shopCollectionGroup;
    public Collection $mainProcessCollectionGroup;
    public array      $excelHeaders;
    public array      $excelContents = [];

    public function __construct(Collection $originalData)
    {
        $this->originalData = $originalData;

        $shopIdGroup = [];
        $this->originalData->each(function (CruiseCheckTaskModel $cruiseCheckTaskModel) use (&$shopIdGroup) {
            $cruiseCheckTaskModel->cruiseTaskGroupsRel->each(function (
                CruiseCheckTaskGroupModel $cruiseCheckTaskGroupModel
            ) use (&$shopIdGroup) {
                $shopIdGroup = array_merge(
                    $shopIdGroup,
                    json_decode(attributeGet($cruiseCheckTaskGroupModel, "shopIds", "[]"), true),
                    []
                );
            });
        });

        $shopIdGroup                      = array_filter(array_unique($shopIdGroup));
        $this->shopCollectionGroup        = ($shopIdGroup ? ShopModel::query()->whereIn("id", $shopIdGroup)->get() : collect([]))->keyBy("id");
        $this->mainProcessCollectionGroup = $shopIdGroup ?
            OpenShopMainProcessModel::query()->select(["shopId", "orderNo"])
                                    ->with([
                                        "userIdentityCardRel" => function (
                                            $query
                                        ) {
                                            $query->select([
                                                "name",
                                                "orderNo"
                                            ]);
                                        }
                                    ])
                                    ->whereIn("shopId", $shopIdGroup)
                                    ->get()->keyBy("shopId") : collect();


    }

    public function array(): array
    {
        // TODO: Implement array() method.
        $this->generateExcelHeader();

        $this->originalData->each(function(CruiseCheckTaskModel $cruiseCheckTaskModel){
             $cruiseCheckTaskModel->cruiseCheckDetailRel->each(function(CruiseCheckDetailModel $checkDetailModel)use($cruiseCheckTaskModel){
                 $cruiseOrder = attributeGet($checkDetailModel, "cruiseOrderRel", null);
                 $shopId = attributeGet($cruiseOrder, "shopId", 0);
                 $addressPrefix = explode(
                     "-",
                     attributeGet($this->shopCollectionGroup, "{$shopId}.addressPrefix", "")
                 );
                 $fsHandlerUserRel = attributeGet($cruiseOrder, "fsHandlerUserRel", null);
                 array_push($this->excelContents, [
                     date("m月", attributeGet($cruiseCheckTaskModel, "createdAt.timestamp", 0)),
                     $cruiseCheckTaskModel->name,
                     attributeGet($this->shopCollectionGroup, "{$shopId}.shopCode", "-"),
                     attributeGet($this->shopCollectionGroup, "{$shopId}.branch", "-"),
                     attributeGet($addressPrefix, "0", "-"),
                     attributeGet($addressPrefix, "1", "-"),
                     attributeGet($this->mainProcessCollectionGroup, "{$shopId}.userIdentityCardRel.name",
                         "-"),
                     attributeGet($this->shopCollectionGroup, "{$shopId}.name", "-"),
                     attributeGet($this->shopCollectionGroup, "{$shopId}.address", "-"),
                     $cruiseCheckTaskModel->statusText,
                     CruiseOrderModel::CRUISE_STATUS_MAPPING[
                     attributeGet($cruiseOrder, "status", null)
                     ] ?? "无",
                     $cruiseCheckTaskModel->id,
                     $fsHandlerUserRel ? vsprintf("%s%s", [
                         $fsHandlerUserRel->name,
                         $fsHandlerUserRel->nickname ? "({$fsHandlerUserRel->nickname})" : ""
                     ]) : "",
                     attributeGet($checkDetailModel, "dealName", "")
                 ]);
            });

        });

        return collect(
            [$this->excelHeaders]
        )->merge($this->excelContents)->toArray();
    }


    public function generateExcelHeader()
    {
        $this->excelHeaders = [
            "月份",
            "任务名称",
            "门店编号",
            "所属区域",
            "门店所载省",
            "门店所在市",
            "加盟商",
            "门店名称",
            "店铺地址",
            "专项任务状态",
            "门店稽核任务状态",
            '任务ID',
            "处理人",
            "巡检人"
        ];
    }
}
